<template>
  <div class="center">
      <n-card :bordered="false">
        <n-space justify="space-between">
          <n-h3 style="margin:0">菜单列表</n-h3>
          <n-button  @click="addMenu">
            <template #icon>
              <n-icon>
                <Add />
              </n-icon>
            </template>
            添加新菜单
          </n-button>
        </n-space>
      </n-card>
      <n-collapse accordion>
          <n-collapse-item style="padding: 16px 0 0 40px;"  v-for="(item,index) in CollapseData" :key="index"  :title="item.menuName" :name="item.id">
            <div style="padding:16px 0 0 22px;display:flex">
              <template v-if="item.children" v-for="(items,index) in item.children" :key="index">
                <div style="flex:1" >{{items.menuName}}</div>
                <div style="flex: 1;justify-content: flex-end;display: flex;padding: 0 20px;">
                  <n-space>
                    <n-button text type="primary" @click.stop="edit(items,items.menuName)">编辑</n-button>
                    <n-button text type="primary" @click.stop="configure(items.id,items.menuName)">配置</n-button>
                    <n-button text type="primary" @click.stop="del(items.id)">删除</n-button>
                  </n-space>
                </div>
              </template>
              <div v-else>
                暂无数据
              </div>
            </div>
            <template #header-extra style="padding:0 20px;">
              <n-space>
                <n-button text type="primary" @click.stop="add(item.id,item.menuName)">添加</n-button>
                <n-button text type="primary" @click.stop="edit(item,item.menuName)">编辑</n-button>
                <n-button text type="primary" @click.stop="del(item.id)">删除</n-button>
              </n-space>
            </template>
          </n-collapse-item>
      </n-collapse>
    <n-modal style="width:50%" v-model:show="Modal" :show-icon="false" preset="dialog" title="Dialog">
      <template #header>
        <div>{{modelTitle}}</div>
      </template>
      <div>
        <BasicTable
          :columns="Modelcolumns"
          :request="Table"
          :actionColumn="actionColumn"
          :row-key="(row) => row.id"
          :pagination="false"
          ref="actionRef"
        >
        </BasicTable>
      </div>
      <template #action style="justify-content: center;">
        <n-button type="primary" size="small" @click="addjurisdiction"> 
            <template #icon>
              <n-icon>
                <Add />
              </n-icon>
            </template>
            添加权限 
        </n-button>
        <n-button size="small" @click="closeModel"> 关闭 </n-button>
      </template>
    </n-modal>
    <Model :showModal="showModal" :labelPlacement="labelPlacement" :FormData="FormData" :formValue="formValue" :title="title" @ModelClick="ModelClick"  @close="close"></Model>
    <ModelBox :ModelBox="ModelBox" :center="center" :title="title" @determine="determine" @close="close"></ModelBox>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive,h,ref, onActivated } from 'vue';
import { BasicTable, TableAction } from '@/components/Table';
import { Model } from '@/components/Model';
import { fetchMenuList,deleteMenu,fetchMenuAuth,addMenuAuth,deleteMenuAuth } from '@/api/menu/index';
import { fetchAuthListPage } from '@/api/Role/index'; //导入接口文件
import { Add } from '@vicons/ionicons5'
import { useRouter } from 'vue-router';
import { ModelBox } from '@/components/ModelBox';
export default defineComponent({
  name:'MenuManagement',
  components: {
    Add,
    ModelBox,
    BasicTable,
    Model
  },
  setup() {
    const ModelBox = ref(false);
    const title = ref(null);
    const center = ref(null);
    const menuId = ref(null);
    const Modal = ref(false);
    const showModal = ref(false);
    const formValue = ref({});
    const actionRef = ref();
    const labelPlacement = ref('left')
    const FormData = ref([
      {
        label: '分配权限',
        show:true,
        type: 'N-tree-select',
        enName: 'authList',
        checkStrategy:'all',
        multiple: true,
        clearable: true,
        checkable: true,
        cascade: true,
        options: [],
        span: 24,
        disabled: false,
        size: 'small',
        placeholder:'请选择权限'
      },
    ])
    const formRef: any = ref(null);
    const modelTitle = ref(null);
    const Modelcolumns = [
      {
        title: '权限名称',
        key: 'authName',
      },
      {
        title: '接口地址',
        key: 'uri',
        render(row) {
          if (row.uri) {
            return row.uri;
          } else {
            return '-';
          }
        },
      },
      {
        title: '备注',
        key: 'remark',
        render(row) {
          if (row.remark) {
            return row.remark;
          } else {
            return '-';
          }
        },
      },
    ];
    const actionColumn = reactive({
      title: '操作',
      key: 'action',
      fixed: 'right',
      render(record) {
        return h(TableAction as any, {
          text: true,
          actions: [
            {
              label: '删除',
              type: 'primary',
              text: true,
              onClick: handleDelete.bind(null, record),
            },
          ],
          select: (key) => {
            message.info(`您点击了，${key} 按钮`);
          },
        });
      },
    });
    const router = useRouter();
    //折叠面板数据
    const CollapseData = ref([]);
    const ArrayData = ref([])
    const menu = async () => {
      CollapseData.value = []
      ArrayData.value =  await fetchMenuList();
      ArrayData.value.map((res) => {
        if(res.parentId == 0){
          CollapseData.value.push(res)
        }
      });
      let request = await recursion(CollapseData.value);
      CollapseData.value = request;
    };
    const handleDelete = async (record: Recordable) => {
      //删除权限
      await deleteMenuAuth(record.id)
      await Table();
      actionRef.value.reload();
    };
    //菜单递归
    const recursion = async (data) => {
      try {
        for(var i = 0; i < data.length; i ++){
            for (var j = 0; j < ArrayData.value.length; j++) {
              if(ArrayData.value[j].parentId == data[i].id){
                if (data[i].hasOwnProperty('children')) {
                  data[i].children.push(ArrayData.value[j])
                } else {
                  data[i].children = []
                  data[i].children.push(ArrayData.value[j])
                }
              }
            }
          if(data[i].children){
            // children若不为空数组，则继续递归调用本方法
            recursion(data[i].children);
          }
        }
      } catch(e){
        console.log(e)
      }
      return data;
    }
    //添加新菜单
    const addMenu = () => {
        router.push({ name: 'addMenu',params: { parentId: 0 }});
    }
    //添加子级菜单
    const add = (id,name) => {
      router.push({ name: 'addMenu',params: { parentId: id,name:`新增子菜单至-${name}` }});
    }
    //更新菜单
    const edit = (item,name) => {
      router.push({ name: 'editMenu',params: { formValue:JSON.stringify(item),name:`编辑信息-${name}` }});
    }
    //删除菜单
    const del = async (id) => {
      menuId.value = id
      ModelBox.value = true;
      title.value = '删除';
      center.value = '是否确定要删除?';
    }
    //配置
    const configure = async (id,name) => {
      menuId.value = id
      modelTitle.value = name
      Modal.value = true;
      //获取权限列表接口
      await Table()
    }
    //模态框关闭
    const close = (e) => {
      showModal.value = e;
    }
    const closeModel = () => {
      Modal.value = false
    }
    //模态框确定
    const ModelClick = async (e) => {
      showModal.value = e;
      const Obj = {...{ menuId:menuId.value },...formValue.value};
      await addMenuAuth(Obj);
      await Table();
      formValue.value = {}
      actionRef.value.reload();
    };
    //删除确定按钮
    const determine = async(e) => {
      ModelBox.value = e;
      await deleteMenu(menuId.value);
      menu()
    };
    //添加权限
    const addjurisdiction = async () => {
      title.value = '添加权限';
      showModal.value = true;
      const data = await fetchAuthListPage();
      const options = data.list.map((res) => {
          return {
              label:res.authName,
              key:res.id
          }
      });
      FormData.value.map((res) => {
          if(res.enName == 'authList'){
              res.options = options
          }
      })
    }
    //获取权限列表数据
    const jurisdictionTable = ref({ list:[] })
    const Table = async () => {
      jurisdictionTable.value.list = []
      if(menuId.value){
        const data = await fetchMenuAuth(menuId.value);
        jurisdictionTable.value.list = data
      }
      return jurisdictionTable.value
    }
    onActivated( async () => {
      menu()
    });
    return {
      Table,
      jurisdictionTable,
      actionRef,
      ArrayData,
      router,
      CollapseData,
      showModal,
      formValue,
      FormData,
      labelPlacement,
      edit,
      configure,
      ModelClick,
      handleDelete,
      addMenu,
      add,
      menu,
      del,
      menuId,
      modelTitle,
      determine,
      addjurisdiction,
      close,
      closeModel,
      ModelBox,
      Modal,
      center,
      formRef,
      title,
      actionColumn,
      Modelcolumns
    };
  },
});
</script>
<style lang="less" scoped>
.center {
  margin: 20px;
  background: #fff;
  height: 100%;
}
.center ::v-deep .n-collapse-item__header-extra{
  padding: 0 20px;
}
</style>
